from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

# 图形验证码
from meiduo_mall.settings.dev import logger


class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpg
        """
        from libs.captcha.captcha import captcha
        text,image = captcha.generate_captcha()
        from django_redis import get_redis_connection
        redis_client = get_redis_connection('verify_image_code')
        # redis_conn.setex()
        redis_client.setex('img_%s' % uuid, 300, text)
        return HttpResponse(image, content_type='image/jpeg')

# 手机短信验证
class SMSCodeView(View):
    """短信验证码"""

    def get(self, request, mobile):
        """
        :param reqeust: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        # sms_codes/(?P<mobile>1[3-9]\d{9})/
        uuid = request.GET.get('image_code_id')
        image_code = request.GET.get('image_code')
        from django_redis import get_redis_connection
        image_redis_client = get_redis_connection('verify_image_code')
        redis_img_code = image_redis_client.get('img_%s'%uuid)

        if redis_img_code is None:
            return JsonResponse({'code': "4001", 'errmsg': '图形验证码失效了'})
        # 注意验证码是byte类型
        if image_code.lower() != redis_img_code.decode().lower():
            return JsonResponse({'code': "4001", 'errmsg': '输入图形验证码有误'})
        try:
            image_redis_client.delete('img_%s'%uuid)
        except Exception as e:
            logger.error(e)

        from random import randint
        sms_code = "%06d" % randint(0, 999999)
        sms_redis_client = get_redis_connection('sms_code')
        sms_redis_client.setex("sms_%s" % mobile, 300, sms_code)

        from libs.yuntongxun.sms import CCP
        CCP().send_template_sms(mobile, [sms_code, 5], 1)
        print("当前验证码是:", sms_code)

        # 5.告诉前端短信发送完毕
        return JsonResponse({'code': '0', 'errmsg': '发送短信成功'})










